package ma.platform.server.student.job;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import jakarta.annotation.Resource;
import ma.platform.server.core.util.StreamUtils;
import ma.platform.server.student.entity.TbComboInfo;
import ma.platform.server.student.entity.TbDateCombo;
import ma.platform.server.student.entity.TbStudent;
import ma.platform.server.student.entity.TbStudentCombo;
import ma.platform.server.student.service.TbComboInfoService;
import ma.platform.server.student.service.TbDateComboService;
import ma.platform.server.student.service.TbStudentComboService;
import ma.platform.server.student.service.TbStudentService;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Component
public class StudentComboJob {

    @Resource
    private TbStudentComboService tbStudentComboService;

    @Resource
    private TbStudentService tbStudentService;

    @Resource
    private TbDateComboService tbDateComboService;

    @Resource
    private TbComboInfoService tbComboInfoService;

    @Transactional(rollbackFor = Exception.class)
    public Integer crateResrve() {
        //获取下周开始时间
        // 创建一个Calendar实例，并将当前时间设置给它
        Calendar calendar = Calendar.getInstance();
        // 获取当前日期是一周中的哪一天，如周一是2，周日是7
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        // 计算距离下周一还有多少天，周一的值为2（因为周日为1），如果今天是周一，那么daysUntilMonday就是0
        int daysUntilMonday = 2 - dayOfWeek;
        if (daysUntilMonday <= -1) { // 如果计算结果是负数或-1，则表示已经过了周一，应该加7天到下一周
            daysUntilMonday += 7;
        }
        // 设置当前时间为下周一的日期
        calendar.add(Calendar.DATE, daysUntilMonday);
        // 输出下周一的日期
        Date nextMonday = calendar.getTime();
        DateTime nextWeekStartTime = DateUtil.beginOfWeek(nextMonday);
        DateTime nextWeekEndTime = DateUtil.endOfWeek(nextMonday);

        List<TbStudentCombo> studentComboList = tbStudentComboService.list(Wrappers.<TbStudentCombo>lambdaQuery().between(TbStudentCombo::getDate, nextWeekStartTime, nextWeekEndTime));
        List<Long> studentList = StreamUtils.convert2List(studentComboList, TbStudentCombo::getStudentId);
        List<Long> createStudentIdList = Lists.newArrayList();
        if (CollectionUtils.isEmpty(studentList)) {
            createStudentIdList = StreamUtils.convert2List(tbStudentService.list(), TbStudent::getId);
        } else {
            createStudentIdList = StreamUtils.convert2List(tbStudentService.list(Wrappers.<TbStudent>lambdaQuery().notIn(TbStudent::getId, studentList)), TbStudent::getId);
        }
        if (CollectionUtils.isEmpty(createStudentIdList)) {
            return 0;
        }
        tbStudentComboService.remove(Wrappers.<TbStudentCombo>lambdaQuery().between(TbStudentCombo::getDate, nextWeekStartTime, nextWeekEndTime).in(TbStudentCombo::getStudentId, createStudentIdList));

        List<TbStudentCombo> crateList = Lists.newArrayList();
        List<DateTime> dateTimes = DateUtil.rangeToList(nextWeekStartTime, nextWeekEndTime, DateField.DAY_OF_YEAR);
        for (DateTime dateTime : dateTimes) {
            List<TbDateCombo> dateComboList = tbDateComboService.list(Wrappers.<TbDateCombo>lambdaQuery().eq(TbDateCombo::getDate, DateUtil.format(dateTime, "yyyy-MM-dd")));
            if (CollectionUtils.isEmpty(dateComboList)) {
                continue;
            }
            List<Long> comboList = StreamUtils.convert2List(dateComboList, TbDateCombo::getComboId);
            List<TbComboInfo> tbComboInfos = tbComboInfoService.listByIds(comboList);
            Map<Long, String> map = StreamUtils.getMap(tbComboInfos, TbComboInfo::getId, TbComboInfo::getName);
            Optional<TbDateCombo> optional = dateComboList.stream().filter(item -> map.getOrDefault(item.getComboId(), "").contains("套餐A")).findFirst();
            TbDateCombo dateCombo = dateComboList.get(0);
            if (optional.isPresent()) {
                dateCombo = optional.get();
            }

            for (Long studentId : createStudentIdList) {
                TbStudentCombo tbStudentCombo = new TbStudentCombo();
                tbStudentCombo.setComboId(dateCombo.getComboId());
                tbStudentCombo.setDateComboId(dateCombo.getId());
                tbStudentCombo.setDate(dateTime);
                tbStudentCombo.setStudentId(studentId);
                crateList.add(tbStudentCombo);
            }
        }
        tbStudentComboService.saveBatch(crateList);
        return 0;
    }

}
